import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.ComponentOrientation;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JMenuBar;

public class MenuBar extends JMenuBar {
	private static final long serialVersionUID = 1118064415833174825L;

	public MenuBar() {
		setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);// 从右到左排列
	}
	
	@Override
	protected void paintComponent(Graphics g) {
		Graphics2D g2d = (Graphics2D) g;// 转化为 Graphics2D 进行绘图
		g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

		// 绘制背景
		g2d.setColor(Color.white);
		// 绘制圆角矩形
		g2d.fillRoundRect(0, 0, getWidth(), getHeight(), 5, 5);

		// 绘制边框
		g2d.setColor(Color.yellow);
		g2d.setStroke(new BasicStroke(2));
		// 绘制圆角矩形边框
		g2d.drawRoundRect(0, 0, getWidth(), getHeight(), 5, 5);

		// 绘制图标
		try {
			// 获取图片资源
			BufferedImage img = ImageIO.read(new File("res/Icon.jpg"));
			img = makeRoundedBorder(img, 100);
			g2d.drawImage(img, 0, 0, 30, getHeight(), this);
		} catch (IOException e) {
			e.printStackTrace();
		}

		// 绘制标题
		g2d.setFont(new Font("微软雅黑", Font.BOLD, 18));
		g2d.setColor(Color.cyan);
		g2d.drawString("垃圾计算器", 40, 20);
	}

	/**
	 * 图片圆角处理
	 * 
	 * @param inputImg  待处理的图片
	 * @param Roundness 圆度
	 * @return 经过圆角处理的图片
	 */
	public BufferedImage makeRoundedBorder(BufferedImage inputImg, int Roundness) {
		int w = inputImg.getWidth();
		int h = inputImg.getHeight();
		BufferedImage outputImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);

		Graphics2D g2d = outputImg.createGraphics();
		g2d.setComposite(AlphaComposite.Src);
		g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		g2d.setColor(Color.WHITE);
		g2d.fill(new RoundRectangle2D.Float(0, 0, w, h, Roundness, Roundness));

		g2d.setComposite(AlphaComposite.SrcAtop);
		g2d.drawImage(inputImg, 0, 0, null);
		// 释放资源
		g2d.dispose();

		return outputImg;
	}
}
